package tvp.ltdd.fake_call_sms.activity;

import java.util.Calendar;
import java.util.Date;

import tvp.ltdd.fake_call_sms.R;
import tvp.ltdd.fake_call_sms.helper.CallLogHelper;
import tvp.ltdd.fake_call_sms.receiver.CallReceiver;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

public class FragmentQuickCall extends Fragment implements OnClickListener,
		OnTouchListener {

	private Button btn15s, btn30s, btn1m, btn5m, btn10m, btnPlus, btnSave,
			btnContact, btnRing;
	private EditText etName;
	private String number = "01234567890";
	private final int PICK = 1;
	private final int RING = 2;
	private final int TIME_DIALOG = 3;
	private final Calendar c = Calendar.getInstance();
	private String ringTonePath = "content://media/internal/audio/media/77";
	private String impath, ringtone;
	private long time = 0;
	private int hour, minute, current_hour, current_minute;
	private long date;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.qck_call, container, false);
		btn15s = (Button) rootView.findViewById(R.id.btn15s);
		btn30s = (Button) rootView.findViewById(R.id.btn30s);
		btn1m = (Button) rootView.findViewById(R.id.btn1m);
		btn5m = (Button) rootView.findViewById(R.id.btn5m);
		btn10m = (Button) rootView.findViewById(R.id.btn10m);
		btnPlus = (Button) rootView.findViewById(R.id.btnPlus);
		btnSave = (Button) rootView.findViewById(R.id.btnSave);
		btnContact = (Button) rootView.findViewById(R.id.btnContact);
		btnRing = (Button) rootView.findViewById(R.id.Rintone);
		etName = (EditText) rootView.findViewById(R.id.etName);

		btn15s.setOnTouchListener(this);
		btn30s.setOnTouchListener(this);
		btn1m.setOnTouchListener(this);
		btn5m.setOnTouchListener(this);
		btn10m.setOnTouchListener(this);
		btnPlus.setOnClickListener(this);
		btnContact.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		btnRing.setOnClickListener(this);

		return rootView;
	}

	@Override
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);
		switch (reqCode) {
		case (PICK):
			if (resultCode == Activity.RESULT_OK) {
				Uri contactData = data.getData();
				Cursor c = getActivity().getContentResolver().query(
						contactData, null, null, null, null);
				if (c.moveToFirst()) {
					String id = c
							.getString(c
									.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

					String hasPhone = c
							.getString(c
									.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

					if (hasPhone.equalsIgnoreCase("1")) {
						Cursor phones = getActivity()
								.getContentResolver()
								.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
										null,
										ContactsContract.CommonDataKinds.Phone.CONTACT_ID
												+ " = " + id, null, null);
						phones.moveToFirst();
						String cNumber = phones
								.getString(phones
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						String nameContact = c
								.getString(c
										.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

						etName.setText(nameContact);
						number = cNumber;
						String phoneId = fetchContactIdFromPhoneNumber(cNumber);
						Long temp = Long.valueOf(phoneId).longValue();
						impath = temp.toString();
						Log.v("image view ", getPhotoUri(temp).toString());

					}
				}
			}
			break;
		case (RING):
			if (resultCode == Activity.RESULT_OK) {

				Uri uri = data
						.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
				if (uri != null) {
					ringTonePath = uri.toString();
					Log.v("*************", ringTonePath);
					Ringtone ring = RingtoneManager.getRingtone(getActivity(),
							uri);
					btnRing.setText(ring.getTitle(getActivity()));
				}

				break;
			}
		case 1111:

			break;
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent1 = new Intent(Intent.ACTION_PICK,
				ContactsContract.Contacts.CONTENT_URI);
		Intent intentRing = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
		intentRing.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,
				ringtone);
		intentRing.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI,
				ringtone);
		switch (v.getId()) {
		case R.id.btnSave:
			if (time > 0) {
				Log.v("fragment call", "btnSave");
				Log.v("call object", "name = " + etName.getText()
						+ " number = " + number + " time = " + time);
				CallReceiver cr = new CallReceiver();
				cr.setCall(getActivity(), etName.getText().toString(), number,
						ringTonePath, impath, System.currentTimeMillis()
								+ (time * 1000), 2, true, 0);
				Toast.makeText(getActivity(), "New call has been placed",
						Toast.LENGTH_SHORT).show();
				getActivity().finish();
			} else if (time < 0) {
				CallLogHelper.insertPlaceholderCall(getActivity()
						.getContentResolver(), etName.getText().toString(),
						number, 2, 0, date);
				Toast.makeText(getActivity(), "New call has been placed",
						Toast.LENGTH_SHORT).show();
				getActivity().finish();
			} else {
				Toast.makeText(getActivity(), "Please set time!",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.btnContact:
			startActivityForResult(intent1, PICK);
			break;
		case R.id.Rintone:
			startActivityForResult(intentRing, 2);
			break;
		case R.id.btnPlus:
			onCreateDialog(TIME_DIALOG).show();
			break;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn15s:
			btn15s.setPressed(true);
			btn30s.setPressed(false);
			btn1m.setPressed(false);
			btn5m.setPressed(false);
			btn10m.setPressed(false);
			btnPlus.setPressed(false);
			time = 15;
			break;
		case R.id.btn30s:
			btn15s.setPressed(false);
			btn30s.setPressed(true);
			btn1m.setPressed(false);
			btn5m.setPressed(false);
			btn10m.setPressed(false);
			btnPlus.setPressed(false);
			time = 30;
			break;
		case R.id.btn1m:
			btn15s.setPressed(false);
			btn30s.setPressed(false);
			btn1m.setPressed(true);
			btn5m.setPressed(false);
			btn10m.setPressed(false);
			btnPlus.setPressed(false);
			time = 60;
			break;
		case R.id.btn5m:
			btn15s.setPressed(false);
			btn30s.setPressed(false);
			btn1m.setPressed(false);
			btn5m.setPressed(true);
			btn10m.setPressed(false);
			btnPlus.setPressed(false);
			time = 300;
			break;
		case R.id.btn10m:
			btn15s.setPressed(false);
			btn30s.setPressed(false);
			btn1m.setPressed(false);
			btn5m.setPressed(false);
			btn10m.setPressed(true);
			btnPlus.setPressed(false);
			time = 600;
			break;
		case R.id.btnPlus:
			btn15s.setPressed(false);
			btn30s.setPressed(false);
			btn1m.setPressed(false);
			btn5m.setPressed(false);
			btn10m.setPressed(false);
			btnPlus.setPressed(true);
			break;
		}
		Log.v("time on touch", "" + time);
		return true;
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG:

			hour = c.get(Calendar.HOUR_OF_DAY);
			minute = c.get(Calendar.MINUTE);
			Log.v("time", "hour = " + hour + " minute = " + minute);
			return new TimePickerDialog(getActivity(), timePickerListener,
					hour, minute + 1, true);

		}
		return null;
	}

	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int selectedHour,
				int selectedMinute) {
			hour = selectedHour;
			minute = selectedMinute;

			// set current time into textview
			btnPlus.setText(new StringBuilder().append(pad(hour)).append(":")
					.append(pad(minute)));
			current_hour = c.get(Calendar.HOUR_OF_DAY);
			current_minute = c.get(Calendar.MINUTE);
			if (current_hour == hour) {
				time = (minute - current_minute) * 60;
			} else {
				time = (((hour - current_hour) * 60 + minute) - current_minute)
						* 60 - c.get(Calendar.SECOND);
			}
			Log.v("time",""+time);
			if (time < 0) {
				c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1,
						c.get(Calendar.DAY_OF_MONTH), selectedHour,
						selectedMinute);
				date = c.getTimeInMillis();
				Log.v("date",""+date);
			}
		}
	};

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	public String fetchContactIdFromPhoneNumber(String phoneNumber) {
		Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
				Uri.encode(phoneNumber));
		Cursor cursor = getActivity().getContentResolver().query(uri,
				new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
				null, null, null);

		String contactId = "";

		if (cursor.moveToFirst()) {
			do {
				contactId = cursor.getString(cursor
						.getColumnIndex(PhoneLookup._ID));
			} while (cursor.moveToNext());
		}

		return contactId;
	}

	public Uri getPhotoUri(long contactId) {
		ContentResolver contentResolver = getActivity().getContentResolver();

		try {
			Cursor cursor = contentResolver
					.query(ContactsContract.Data.CONTENT_URI,
							null,
							ContactsContract.Data.CONTACT_ID
									+ "="
									+ contactId
									+ " AND "

									+ ContactsContract.Data.MIMETYPE
									+ "='"
									+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
									+ "'", null, null);

			if (cursor != null) {
				if (!cursor.moveToFirst()) {
					return null; // no photo
				}
			} else {
				return null; // error in cursor process
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		Uri person = ContentUris.withAppendedId(
				ContactsContract.Contacts.CONTENT_URI, contactId);
		return Uri.withAppendedPath(person,
				ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
	}

}
